<template>
  <div id="contianer">
    <div>
      <el-row :gutter="30">
        <el-form
          ref="uploadForm"
          :model="uploadForm"
          :rules="rules"
          label-width="80px"
        >
          <el-col :span="12">
            <el-form-item label="课程名称" prop="folderName">
              <el-input v-model.trim="uploadForm.folderName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者姓名" prop="author">
              <el-input v-model.trim="uploadForm.author" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="课程简介" prop="introduction">
              <el-input
                maxlength="200"
                show-word-limit placeholder="请输入"
                v-model.trim="uploadForm.introduction"
                type="textarea"
                :rows="3"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <hr style="border-top: 1px solid #d8d8d8" />
      <el-row :gutter="20">
        <el-col :span="8">
          <h2>视频组菜单</h2>
          <vxe-table
            show-overflow
            keep-source
            ref="tableRef"
            :row-config="{
              keyField: 'id',
              isCurrent: true,
              isHover: true,
            }"
            :column-config="{ resizable: true }"
            :print-config="{}"
            :export-config="{}"
            :loading="loading"
            :tree-config="{
              transform: false,
              rowField: 'id',
              parentField: 'parentId',
              expandAll: true,
            }"
            :data="tableData"
            @cell-click="currentChangeEvent"
          >
            <vxe-column
              field="chapterName"
              title="名称"
              tree-node
              :edit-render="{}"
            >
              <template #edit="{ row, rowIndex }">
                <span v-if="rowIndex === 0">{{row.chapterName}}</span>
                <vxe-input v-else v-model="row.chapterName" type="text"></vxe-input>
              </template>
            </vxe-column>
<!--            <vxe-column type="expand" width="100" title="文件">
              <template #content="{ row }">
                <ul
                  class="expand-wrapper"
                  v-for="(item, index) in row.videoList"
                  :key="index"
                >
                  <li style="display: flex; space-between: space-between">
                    <span>{{ item.videoType === 0 ? "课件：" : "视频：" }}</span
                    ><span>{{ item.fileName }}</span>
                  </li>
                </ul>
              </template>
            </vxe-column>-->
            <vxe-column title="操作" width="120">
              <template #default="{ row }">
                <el-button
                  type="text"
                  @click.stop="insertRow(row)"
                  v-if="!isPreview && row.level < 3"
                  >{{ row.level === 1 ? "添加章" : "添加节" }}</el-button>
                <vxe-button
                  type="text"
                  style="color: #ff4949"
                  @click.stop="removeRow(row)"
                  v-if="!isPreview && row.level > 1">删除</vxe-button>
              </template>
            </vxe-column>
          </vxe-table>
        </el-col>
        <el-col :span="16" style="border-left: 1px solid #d8d8d8">
          <el-tag v-if="chooseChapter" style="margin: 15px 0"
            >上传至 {{ chooseChapter }}</el-tag
          >
          <el-tag v-else style="margin: 15px 0" type="danger"
            >请选择导入至哪一章节</el-tag
          >
          <div class="file_box">
            <el-table
              :data="fileTable"
              v-loading="loading"
              border
              size="medium"
              class="table"
            >
              <el-table-column
                label="序号"
                align="center"
                width="60"
                fixed="left"
              >
                <template slot-scope="scope">
                  <span>{{ scope.$index + 1 }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="fileName"
                label="文件名称"
                fixed="left"
                width="150"
              >
                <!-- <template slot-scope="scope">
                                    <el-link
                                        type="primary"
                                        :underline="false"
                                        @click="edit(scope.row.id)"
                                        >{{ scope.row.fileName }}</el-link
                                    >
                                </template> -->
              </el-table-column>
              <el-table-column prop="fileCode" label="文件编号">
              </el-table-column>
              <el-table-column prop="fileVersion" label="文件版次">
              </el-table-column>
              <el-table-column prop="versionStatus" label="版次状态">
                <template slot-scope="scope">
                  <span>{{
                    scope.row.versionStatus === 0 ? "废止" : "现行"
                  }}</span>
                </template>
              </el-table-column>

              <el-table-column prop="author" label="作者姓名">
              </el-table-column>
              <el-table-column prop="uploadUser" label="上传人员">
              </el-table-column>
              <el-table-column prop="uploadTime" label="上传日期">
              </el-table-column>

              <el-table-column prop="fileTypeName" label="文件类型">
              </el-table-column>
              <el-table-column prop="professionName" label="所属专业">
              </el-table-column>
              <el-table-column prop="fileFormat" label="文件格式">
              </el-table-column>

              <el-table-column prop="statusName" label="文件状态">
              </el-table-column>
              <el-table-column prop="analyseStatusName" label="解析状态">
              </el-table-column>
              <el-table-column
                fixed="right"
                header-align="center"
                align="center"
                width="260"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="previewFn(scope.row)"
                    size="small"
                    >查看</el-button
                  >
                  <el-button
                    type="text"
                    size="small"
                    @click="handleFile(scope.row)"
                    v-if="!isPreview && scope.row.permissionVo.submit"
                    >提交
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="withdraw(scope.row)"
                    v-if="!isPreview && scope.row.permissionVo.withdraw"
                    >撤回
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    @click="delFn(scope.row)"
                    v-if="!isPreview && scope.row.permissionVo.delete"
                    >删除
                  </el-button>
                  <el-upload
                    style="display: inline; margin-left: 12px"
                    v-if="!isPreview && !isVideoGroup && scope.row.permissionVo.update"
                    class="upload-demo"
                    :action="uploadImgUrl"
                    :on-success="
                      (response, file, fileList) => {
                        return uploadSuccess(
                          response,
                          file,
                          fileList,
                          scope.row
                        );
                      }
                    "
                    :show-file-list="false"
                    :headers="headers"
                  >
                    <el-button type="text" size="small">更新</el-button>
                  </el-upload>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 预览 -->
    <el-dialog
      class="preview"
      :visible.sync="videoVideoVisible"
      :close-on-click-modal="false"
      width="100vw"
      center
    >
      <div class="video_model">
        <div id="video"></div>
        <!-- <div class="video_info">
                    <span class="title">
                        <h3>{{ dataInfo.fileName }}</h3>
                    </span>
                </div> -->
      </div>
    </el-dialog>
    <PdfPreview ref="pdf_preview_pef"></PdfPreview>
  </div>
</template>
<script>
import PdfPreview from './PdfPreview'
export default {
  data() {
    return {
      videoVideoVisible: false,
      loading: false,
      chooseChapter: "",
      uploadForm: {
        folderName: "",
        author: "",
        introduction: "",
      },
      currentRow: {},
      tableData: [],
      rules: {
        folderName: [
          { required: true, message: "请输入课程名称", trigger: "change" },
        ],
        author: [
          { required: true, message: "请输入作者姓名", trigger: "change" },
        ],
        introduction: [
          { required: true, message: "请输入课程简介", trigger: "change" },
        ],
      },
      fileTable: [],
      headers: {
        token: localStorage.getItem("token"),
      },
      uploadImgUrl: this.$config.VUE_APP_BASE_API + "/file/upload", // 上传的图片服务器地址
      isVideosUpload: false,
      chooseId: '',
      isPreview: false,
    };
  },
  components: {
    PdfPreview
  },
  mounted() {
    this.getVideoDetail();
    this.isVideoGroup = this.$route.query.isVideoGroup;
    this.isPreview = this.$route.query.isPreview;
  },
  methods: {
    getVideoDetail() {
      this.$http({
        url: "/knowledgeFile/video/detail",
        method: "get",
        params: {
          id: this.$route.query.id,
        },
      }).then(({ data }) => {
        console.log("data", data);
        if (data.code == 200) {
          this.uploadForm = data.data.course;
          this.tableData = data.data.video && [data.data.video];
        }
      });
    },
    // 附件上传成功
    uploadSuccess(res, file, fileList, row) {
      console.log(res, "res", file, row);
      this.$http({
        url: "/knowledgeFile/file/update",
        method: "post",
        data: {
          fileType: this.uploadForm.fileType,
          author: this.uploadForm.author,
          profession: this.uploadForm.profession,
          fileName: row.fileName,
          fileId: res.data.id,
          id: row.id,
        },
      })
        .then(({ data }) => {
          if (data.code == 200) {
            this.$message.success("更新成功");
            this.getVideoDetail();
            setTimeout(() => {
              const node = this.findNodeById(this.tableData, this.chooseId.id)
              this.fileTable = node.videoList
            }, 1000)
          } else {
            this.$message.error("更新失败");
          }
        })
        .catch((err) => {
          this.$message.error("更新失败");
        });
    },
    previewFn(row) {
      this.$http({
        url: "/knowledgeData/preview",
        method: "get",
        params: {
          id: row.id,
        },
      }).then(({ data }) => {
        console.log('row.readAuthority', row.readAuthority)
        if (!row.readAuthority) {
          this.$message.warning("文件正在解析中，不可预览");
          return;
        }
        if (row.fileFormat == 'ppt' || row.fileFormat == 'pptx' || row.fileFormat == 'pdf' || row.fileFormat == 'doc') {
            this.$nextTick(() => {
              this.$refs.pdf_preview_pef.init({downloadUrl: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl})
            })
        } else {
          this.videoVideoVisible = true;
          console.log("获取文件之后地址", data.data.downloadUrl);
          this.previewVideoVisible = true;
          setTimeout(() => {
            new this.$Player({
              id: "video", // 元素id
              lang: "zh", // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              height: 200,
              // 视频地址
              url: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2], // 传入倍速可选数组
            });
          }, 300);
        }
      });
    },
    async insertRow(currRow) {
      const $table = this.$refs.tableRef;
      // // 如果 null 则插入到目标节点顶部
      // // 如果 -1 则插入到目标节点底部
      // // 如果 row 则有插入到效的目标节点该行的位置
      const rid = Date.now();
      const number = currRow.children?currRow.children.length + 1:1;
      const title = currRow.level === 1 ? "章" : "节";
      const record = {
        chapterName: `第${number}${title}`,
        // id: rid,
        chapter: rid,
        // parentId: currRow.id, // 需要指定父节点，自动插入该节点中
        level: currRow.level + 1,
        hasChildren: false,
        children: [],
        videoList: [],
      };
      if (currRow.children || currRow.children === []) {
        currRow.children = currRow.children.concat(record);
      } else {
        currRow.children = [record];
      }
      $table.reloadTreeExpand(currRow);
      $table.setAllTreeExpand(true)
      $table.remove({});
      // const { row: newRow } = await $table.insertAt(record, -1)
      // await $table.setTreeExpand(currRow, true) // 将父节点展开
      // await $table.setEditRow(newRow) // 插入子节点
      // this.$set(item, 'chapterName', newVal)
      // currRow.children.push(record)
      // this.tableData.push(record)
    },

    async removeRow(row) {
      if (row.videoList && row.videoList.length > 0) {
        this.$message.error("删除失败！该章节下存在文件，请删除文件后操作！");
      } else {
        this.tableData[0].children.forEach((item, index) => {
          console.log(row, "rowwwwwwww", this.tableData);
          if (item.chapter === row.chapter) {
            this.tableData[0].children.splice(index, 1);
          } else {
            item.children &&
            item.children.forEach((i, indexNum) => {
              console.log(row, "rowwwwwwww11111111111", this.tableData);
              if (i.chapter === row.chapter) {
                item.children.splice(indexNum, 1);
              }
            });
          }
        });
        const $table = this.$refs.tableRef;
        await $table.remove(row);
        $table.reloadTreeExpand(row);
      }
    },
    currentChangeEvent({ row }) {
      console.log(row, "行选中事件");
      this.chooseChapter = row.chapterName;
      this.currentRow = row;
      this.fileTable = row.videoList;
      this.chooseId = row.id;
    },
    delFn(row) {
      console.log(row, this.fileTable, "ffff");
      this.$confirm(
        `确定删除${row ? "[" + row.fileName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeFile/file/delete",
          method: "post",
          data: { id: row.id },
        }).then(({ data }) => {
          this.$message.success(data.msg);
          this.fileTable = this.fileTable.filter((item) => item.id !== row.id);
          const rowTable = this.$refs.tableRef.getCurrentRecord();
          rowTable.videoList = rowTable.videoList.filter(item => item.fileName !== row.fileName);
        });
      });
    },
    handleFile(row) {
      this.$confirm(
        `确定提交${row ? "[" + row.fileName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeFile/file/submit",
          method: "post",
          data: { id: row.id },
        }).then(({ data }) => {
          this.$message.success(data.msg);
          this.getVideoDetail();
          setTimeout(() => {
            const node = this.findNodeById(this.tableData, this.chooseId.id)
            this.fileTable = node.videoList
          }, 1000)
        });
      });
    },
    withdraw(row) {
      this.$confirm(
        `确定撤回${row ? "[" + row.fileName + "]" : "选中项"}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        this.$http({
          url: "/knowledgeFile/file/withdraw",
          method: "post",
          data: { id: row.id },
        }).then(({ data }) => {
          this.$message.success(data.msg);
          this.getVideoDetail();
          setTimeout(() => {
            const node = this.findNodeById(this.tableData, this.chooseId.id)
            this.fileTable = node.videoList
          }, 1000)
        });
      });
    },
    findNodeById(data, id) {
      for (let item of data) {
        if (item.id == id) {
          return item;
        }
        if (item.children && item.children.length > 0) {
          const result = this.findNodeById(item.children, this.chooseId);
          if (result) {
            return result;
          }
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
#contianer {
  width: 100%;
  height: 100%;
  background: #fff;
  padding: 50px;
  h2 {
    font-size: 20px;
    font-weight: 550;
  }
}
.preview ::v-deep.el-dialog__body {
  width: 100vw !important;
  height: 96vh !important;
  display: flex !important;
  justify-content: space-around;
}
.preview ::v-deep.el-dialog__footer {
  margin-top: -65px !important;
}
.preview ::v-deep.el-dialog {
  margin-top: 0px !important;
}

.video_model {
  // width: 260px;
  // height: 190px;
  width: 100%;
  // height: 85vh !important;
  // background: red;
  // border: 1px solid #e6e6e6;
  border-radius: 5px;
  margin-bottom: 20px;

  #video {
    flex: auto;
    height: 85vh !important;
  }

  .video_info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10px;
    line-height: 22px;

    h3 {
      flex: 1;
      padding: 0;
      margin: 0;
      font-weight: 550;
      font-size: 18x;
    }

    .author,
    .blurb {
      font-size: 14px;
    }
  }
}
</style>
